import {
  AccountState,
  NormalState, OverdraftState, RestrictedState,
  AccountStateLevel
} from './State';

interface IAccount{
  deposit(amount:number):void; // 存款
  withdraw(amount:number):void; // 取款
  calcInterest():number; // 计算利息
}

class Account implements IAccount{
  private owner:string; // 开户姓名
  private balance:number; // 余额
  private state:AccountState; // 状态
  constructor(name:string, amount:number){
    this.owner = name;
    this.balance = amount;
    this.state = new NormalState(this);
    console.log(`账户初始状态为[${this.state.name}]状态，余额${this.balance}元`);
  }
  deposit(amount:number):void{
    console.log(`%c存款${amount}`, 'color:green');
    this.state.deposit(amount);
  }
  withdraw(amount:number):void{
    console.log(`%c尝试取款${amount}`, 'color:blue');
    try{
      this.state.withdraw(amount);
    }catch(err){
      console.log(`%c取款失败：${err.message}`, 'color:red');
    }
  }
  calcInterest():number{
    return this.state.calcInterest();
  }
  // 获取余额
  getBalance():number{
    return this.balance;
  }
  // 设置余额
  setBalance(balance:number){
    this.balance = balance;
    console.log(`余额${balance}`);

    let isChanged = false;
    // 变更状态
    if(balance > 0){
      if(this.state.level !== AccountStateLevel.Normal){
        isChanged = true;
        this.state = new NormalState(this);
      }
    }else if(balance < 0 && balance >= -2000){
      if(this.state.level !== AccountStateLevel.Overdraft) {
        isChanged = true;
        this.state = new OverdraftState(this);
      }
    }else if(balance < -2000){
      if(this.state.level !== AccountStateLevel.Restricted) {
        isChanged = true;
        this.state = new RestrictedState(this);
      }
    }

    if(isChanged){ console.log(`账户状态变更为[${this.state.name}]`); }
  }
}

export {
  IAccount,
  Account
};